/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MeteoCal.controller;

import MeteoCal.bean.exceptions.IllegalOrphanException;
import MeteoCal.bean.exceptions.NonexistentEntityException;
import MeteoCal.bean.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import MeteoCal.entity.Event;
import MeteoCal.entity.Notification;
import MeteoCal.entity.Receivednotification;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author Daniele
 */
public class NotificationJpaController implements Serializable {

    public NotificationJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Notification notification) throws RollbackFailureException, Exception {
        if (notification.getReceivednotificationCollection() == null) {
            notification.setReceivednotificationCollection(new ArrayList<Receivednotification>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Event idEvent = notification.getIdEvent();
            if (idEvent != null) {
                idEvent = em.getReference(idEvent.getClass(), idEvent.getIdEvent());
                notification.setIdEvent(idEvent);
            }
            Collection<Receivednotification> attachedReceivednotificationCollection = new ArrayList<Receivednotification>();
            for (Receivednotification receivednotificationCollectionReceivednotificationToAttach : notification.getReceivednotificationCollection()) {
                receivednotificationCollectionReceivednotificationToAttach = em.getReference(receivednotificationCollectionReceivednotificationToAttach.getClass(), receivednotificationCollectionReceivednotificationToAttach.getReceivednotificationPK());
                attachedReceivednotificationCollection.add(receivednotificationCollectionReceivednotificationToAttach);
            }
            notification.setReceivednotificationCollection(attachedReceivednotificationCollection);
            em.persist(notification);
            if (idEvent != null) {
                idEvent.getNotificationCollection().add(notification);
                idEvent = em.merge(idEvent);
            }
            for (Receivednotification receivednotificationCollectionReceivednotification : notification.getReceivednotificationCollection()) {
                Notification oldNotificationOfReceivednotificationCollectionReceivednotification = receivednotificationCollectionReceivednotification.getNotification();
                receivednotificationCollectionReceivednotification.setNotification(notification);
                receivednotificationCollectionReceivednotification = em.merge(receivednotificationCollectionReceivednotification);
                if (oldNotificationOfReceivednotificationCollectionReceivednotification != null) {
                    oldNotificationOfReceivednotificationCollectionReceivednotification.getReceivednotificationCollection().remove(receivednotificationCollectionReceivednotification);
                    oldNotificationOfReceivednotificationCollectionReceivednotification = em.merge(oldNotificationOfReceivednotificationCollectionReceivednotification);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Notification notification) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Notification persistentNotification = em.find(Notification.class, notification.getIdNotification());
            Event idEventOld = persistentNotification.getIdEvent();
            Event idEventNew = notification.getIdEvent();
            Collection<Receivednotification> receivednotificationCollectionOld = persistentNotification.getReceivednotificationCollection();
            Collection<Receivednotification> receivednotificationCollectionNew = notification.getReceivednotificationCollection();
            List<String> illegalOrphanMessages = null;
            for (Receivednotification receivednotificationCollectionOldReceivednotification : receivednotificationCollectionOld) {
                if (!receivednotificationCollectionNew.contains(receivednotificationCollectionOldReceivednotification)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Receivednotification " + receivednotificationCollectionOldReceivednotification + " since its notification field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idEventNew != null) {
                idEventNew = em.getReference(idEventNew.getClass(), idEventNew.getIdEvent());
                notification.setIdEvent(idEventNew);
            }
            Collection<Receivednotification> attachedReceivednotificationCollectionNew = new ArrayList<Receivednotification>();
            for (Receivednotification receivednotificationCollectionNewReceivednotificationToAttach : receivednotificationCollectionNew) {
                receivednotificationCollectionNewReceivednotificationToAttach = em.getReference(receivednotificationCollectionNewReceivednotificationToAttach.getClass(), receivednotificationCollectionNewReceivednotificationToAttach.getReceivednotificationPK());
                attachedReceivednotificationCollectionNew.add(receivednotificationCollectionNewReceivednotificationToAttach);
            }
            receivednotificationCollectionNew = attachedReceivednotificationCollectionNew;
            notification.setReceivednotificationCollection(receivednotificationCollectionNew);
            notification = em.merge(notification);
            if (idEventOld != null && !idEventOld.equals(idEventNew)) {
                idEventOld.getNotificationCollection().remove(notification);
                idEventOld = em.merge(idEventOld);
            }
            if (idEventNew != null && !idEventNew.equals(idEventOld)) {
                idEventNew.getNotificationCollection().add(notification);
                idEventNew = em.merge(idEventNew);
            }
            for (Receivednotification receivednotificationCollectionNewReceivednotification : receivednotificationCollectionNew) {
                if (!receivednotificationCollectionOld.contains(receivednotificationCollectionNewReceivednotification)) {
                    Notification oldNotificationOfReceivednotificationCollectionNewReceivednotification = receivednotificationCollectionNewReceivednotification.getNotification();
                    receivednotificationCollectionNewReceivednotification.setNotification(notification);
                    receivednotificationCollectionNewReceivednotification = em.merge(receivednotificationCollectionNewReceivednotification);
                    if (oldNotificationOfReceivednotificationCollectionNewReceivednotification != null && !oldNotificationOfReceivednotificationCollectionNewReceivednotification.equals(notification)) {
                        oldNotificationOfReceivednotificationCollectionNewReceivednotification.getReceivednotificationCollection().remove(receivednotificationCollectionNewReceivednotification);
                        oldNotificationOfReceivednotificationCollectionNewReceivednotification = em.merge(oldNotificationOfReceivednotificationCollectionNewReceivednotification);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = notification.getIdNotification();
                if (findNotification(id) == null) {
                    throw new NonexistentEntityException("The notification with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Notification notification;
            try {
                notification = em.getReference(Notification.class, id);
                notification.getIdNotification();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The notification with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Receivednotification> receivednotificationCollectionOrphanCheck = notification.getReceivednotificationCollection();
            for (Receivednotification receivednotificationCollectionOrphanCheckReceivednotification : receivednotificationCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Notification (" + notification + ") cannot be destroyed since the Receivednotification " + receivednotificationCollectionOrphanCheckReceivednotification + " in its receivednotificationCollection field has a non-nullable notification field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Event idEvent = notification.getIdEvent();
            if (idEvent != null) {
                idEvent.getNotificationCollection().remove(notification);
                idEvent = em.merge(idEvent);
            }
            em.remove(notification);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Notification> findNotificationEntities() {
        return findNotificationEntities(true, -1, -1);
    }

    public List<Notification> findNotificationEntities(int maxResults, int firstResult) {
        return findNotificationEntities(false, maxResults, firstResult);
    }

    private List<Notification> findNotificationEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Notification.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Notification findNotification(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Notification.class, id);
        } finally {
            em.close();
        }
    }

    public int getNotificationCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Notification> rt = cq.from(Notification.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
